const { pool } = require('../config/db');

/**
 * 获取所有场景模式 (包括系统预设和用户自定义)
 */
async function getAllSceneModes(req, res) {
  try {
    const userId = req.user ? req.user.id : null; // 如果有用户登录，则包含用户自定义场景
    let query = 'SELECT * FROM scene_modes WHERE is_system_preset = 1';
    const queryParams = [];

    if (userId) {
      query += ' OR user_id = ?';
      queryParams.push(userId);
    }
    query += ' ORDER BY is_system_preset DESC, name ASC';

    const [rows] = await pool.query(query, queryParams);

    const sceneModes = rows.map(scene => ({
      id: scene.id,
      name: scene.name,
      icon: scene.icon,
      isSystemPreset: scene.is_system_preset === 1,
      userId: scene.user_id,
      settings: JSON.parse(scene.settings || '{}') // 解析JSON字符串
    }));

    res.json({
      success: true,
      data: sceneModes
    });
  } catch (error) {
    console.error('获取场景模式列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取场景模式列表失败',
      error: error.message
    });
  }
}

/**
 * 获取特定场景模式信息
 */
async function getSceneModeById(req, res) {
  try {
    const { id } = req.params;
    const userId = req.user ? req.user.id : null;

    const [rows] = await pool.query('SELECT * FROM scene_modes WHERE id = ?', [id]);

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '场景模式未找到'
      });
    }

    const scene = rows[0];

    // 验证用户权限 (用户只能获取自己的非预设场景)
    if (!scene.is_system_preset && scene.user_id !== userId) {
        return res.status(403).json({
            success: false,
            message: '无权访问此场景模式'
        });
    }

    res.json({
      success: true,
      data: {
        id: scene.id,
        name: scene.name,
        icon: scene.icon,
        isSystemPreset: scene.is_system_preset === 1,
        userId: scene.user_id,
        settings: JSON.parse(scene.settings || '{}')
      }
    });
  } catch (error) {
    console.error('获取场景模式信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取场景模式信息失败',
      error: error.message
    });
  }
}

/**
 * 获取系统预设场景模式
 */
async function getSystemPresetSceneModes(req, res) {
    try {
        const [rows] = await pool.query('SELECT * FROM scene_modes WHERE is_system_preset = 1 ORDER BY name ASC');
        const sceneModes = rows.map(scene => ({
            id: scene.id,
            name: scene.name,
            icon: scene.icon,
            isSystemPreset: true,
            settings: JSON.parse(scene.settings || '{}')
        }));
        res.json({ success: true, data: sceneModes });
    } catch (error) {
        console.error('获取系统预设场景模式失败:', error);
        res.status(500).json({ success: false, message: '获取系统预设场景模式失败', error: error.message });
    }
}

/**
 * 获取用户自定义场景模式
 */
async function getUserDefinedSceneModes(req, res) {
    try {
        const userId = req.user.id;
        const [rows] = await pool.query('SELECT * FROM scene_modes WHERE user_id = ? AND is_system_preset = 0 ORDER BY name ASC', [userId]);
        const sceneModes = rows.map(scene => ({
            id: scene.id,
            name: scene.name,
            icon: scene.icon,
            isSystemPreset: false,
            userId: scene.user_id,
            settings: JSON.parse(scene.settings || '{}')
        }));
        res.json({ success: true, data: sceneModes });
    } catch (error) {
        console.error('获取用户自定义场景模式失败:', error);
        res.status(500).json({ success: false, message: '获取用户自定义场景模式失败', error: error.message });
    }
}


/**
 * 创建新场景模式 (用户自定义)
 */
async function createSceneMode(req, res) {
  try {
    const userId = req.user.id;
    const { name, icon, settings } = req.body;

    if (!name || !settings) {
      return res.status(400).json({
        success: false,
        message: '场景名称和设置是必需的'
      });
    }

    // 将settings对象转换为JSON字符串存储
    const settingsString = JSON.stringify(settings);

    const [result] = await pool.query(
      'INSERT INTO scene_modes (user_id, name, icon, settings, is_system_preset) VALUES (?, ?, ?, ?, 0)',
      [userId, name, icon || 'default_icon', settingsString]
    );

    res.status(201).json({
      success: true,
      message: '场景模式已创建',
      data: {
        id: result.insertId,
        name,
        icon: icon || 'default_icon',
        isSystemPreset: false,
        userId,
        settings
      }
    });
  } catch (error) {
    console.error('创建场景模式失败:', error);
    res.status(500).json({
      success: false,
      message: '创建场景模式失败',
      error: error.message
    });
  }
}

/**
 * 更新场景模式 (只能更新用户自定义的)
 */
async function updateSceneMode(req, res) {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    const { name, icon, settings } = req.body;

    // 检查场景是否存在且属于当前用户且非系统预设
    const [scenes] = await pool.query(
      'SELECT * FROM scene_modes WHERE id = ? AND user_id = ? AND is_system_preset = 0',
      [id, userId]
    );

    if (scenes.length === 0) {
      return res.status(404).json({
        success: false,
        message: '场景模式未找到或无权更新'
      });
    }

    const updateFields = {};
    if (name) updateFields.name = name;
    if (icon) updateFields.icon = icon;
    if (settings) updateFields.settings = JSON.stringify(settings);

    if (Object.keys(updateFields).length === 0) {
        return res.status(400).json({
            success: false,
            message: '没有提供要更新的字段'
        });
    }

    await pool.query('UPDATE scene_modes SET ? WHERE id = ?', [updateFields, id]);

    res.json({
      success: true,
      message: '场景模式已更新',
      data: {
        id: parseInt(id),
        ...updateFields,
        settings: settings ? settings : JSON.parse(scenes[0].settings || '{}') // 返回解析后的settings
      }
    });
  } catch (error) {
    console.error('更新场景模式失败:', error);
    res.status(500).json({
      success: false,
      message: '更新场景模式失败',
      error: error.message
    });
  }
}

/**
 * 删除场景模式 (只能删除用户自定义的)
 */
async function deleteSceneMode(req, res) {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const [result] = await pool.query(
      'DELETE FROM scene_modes WHERE id = ? AND user_id = ? AND is_system_preset = 0',
      [id, userId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '场景模式未找到或无权删除'
      });
    }

    res.json({
      success: true,
      message: '场景模式已删除',
      data: { id: parseInt(id) }
    });
  } catch (error) {
    console.error('删除场景模式失败:', error);
    res.status(500).json({
      success: false,
      message: '删除场景模式失败',
      error: error.message
    });
  }
}

/**
 * 激活场景模式
 * 注意：此功能的具体实现会比较复杂，涉及到与设备控制器的交互
 * 这里仅做状态记录的简化版
 */
async function activateSceneMode(req, res) {
  try {
    const { id } = req.params;
    const userId = req.user.id; // 假设激活场景需要用户登录

    // 1. 验证场景模式是否存在
    const [scenes] = await pool.query('SELECT * FROM scene_modes WHERE id = ?', [id]);
    if (scenes.length === 0) {
      return res.status(404).json({ success: false, message: '场景模式未找到' });
    }
    const scene = scenes[0];

    // 2. 验证用户权限 (如果是用户自定义场景)
    if (!scene.is_system_preset && scene.user_id !== userId) {
        return res.status(403).json({ success: false, message: '无权激活此场景模式' });
    }

    // 3. 更新当前激活的场景 (简化：假设有一个表或字段记录当前激活场景)
    // 在实际应用中，你可能需要一个专门的表来存储用户当前的激活状态
    // 或者，激活场景会触发一系列设备控制指令
    await pool.query('UPDATE user_preferences SET active_scene_id = ? WHERE user_id = ?', [id, userId]);

    // 4. TODO: 应用场景设置到设备 (调用deviceController或相关服务)
    // const sceneSettings = JSON.parse(scene.settings || '{}');
    // applySceneToDevices(userId, sceneSettings);

    res.json({
      success: true,
      message: `场景模式 "${scene.name}" 已激活`,
      data: {
        activeSceneId: id,
        sceneName: scene.name
      }
    });
  } catch (error) {
    console.error('激活场景模式失败:', error);
    res.status(500).json({
      success: false,
      message: '激活场景模式失败',
      error: error.message
    });
  }
}

/**
 * 获取当前激活的场景模式
 */
async function getActiveSceneMode(req, res) {
    try {
        const userId = req.user.id;
        const [prefs] = await pool.query('SELECT active_scene_id FROM user_preferences WHERE user_id = ?', [userId]);

        if (prefs.length === 0 || !prefs[0].active_scene_id) {
            return res.json({ success: true, data: null, message: '当前没有激活的场景模式' });
        }

        const activeSceneId = prefs[0].active_scene_id;
        const [scenes] = await pool.query('SELECT * FROM scene_modes WHERE id = ?', [activeSceneId]);

        if (scenes.length === 0) {
            // 活动场景ID存在但场景本身被删除的情况
            await pool.query('UPDATE user_preferences SET active_scene_id = NULL WHERE user_id = ?', [userId]);
            return res.json({ success: true, data: null, message: '之前激活的场景模式已不存在' });
        }
        
        const scene = scenes[0];
        res.json({
            success: true,
            data: {
                id: scene.id,
                name: scene.name,
                icon: scene.icon,
                isSystemPreset: scene.is_system_preset === 1,
                userId: scene.user_id,
                settings: JSON.parse(scene.settings || '{}')
            }
        });
    } catch (error) {
        console.error('获取当前激活场景失败:', error);
        res.status(500).json({ success: false, message: '获取当前激活场景失败', error: error.message });
    }
}


module.exports = {
  getAllSceneModes,
  getSceneModeById,
  getSystemPresetSceneModes,
  getUserDefinedSceneModes,
  createSceneMode,
  updateSceneMode,
  deleteSceneMode,
  activateSceneMode,
  getActiveSceneMode
};